import axios from "axios"
import { useUserStore } from "@/stores/userStore"

// 创建axios实例
const request = axios.create({
   baseURL: '/api',
   timeout: 5000, // 请求超时时间
   headers: {
    'Content-Type': 'application/json',
  },
})

// axios请求拦截器
request.interceptors.request.use(config => {
  try {
    // 从用户store中获取token
    const userStore = useUserStore()
    const token = userStore.userInfo?.data?.token
    
    // 如果有token，则添加到请求头中
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      console.log('添加token到请求头:', `Bearer ${token.substring(0, 20)}...`)
    } else {
      console.log('未找到token')
    }
  } catch (error) {
    console.error('获取token时出错:', error)
  }
  
  console.log('发送请求:', {
    url: config.url,
    method: config.method,
    headers: {
      ...config.headers,
      // 避免在日志中暴露完整token
      Authorization: config.headers.Authorization ? 
        config.headers.Authorization.replace(/Bearer\s+(\S{5}).*/, 'Bearer $1***') : 
        undefined
    },
    params: config.params,
    data: config.data
  })
  
  return config
}), e => Promise.reject(e)

// axios响应拦截器
request.interceptors.response.use(res => {
  console.log('收到响应:', {
    status: res.status,
    data: res.data,
    headers: res.headers
  })
  return res.data
}, e => {
  console.error('请求失败:', e)
  return Promise.reject(e)
})

export default request